<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI 集成快速测试</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      min-height: 100vh;
    }
    .container {
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      border-radius: 15px;
      padding: 30px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    }
    .button {
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      border-radius: 8px;
      padding: 12px 24px;
      margin: 10px;
      cursor: pointer;
      transition: all 0.3s ease;
      color: white;
      font-weight: 500;
    }
    .button:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    }
    .button:disabled {
      opacity: 0.5;
      cursor: not-allowed;
      transform: none;
    }
    .result {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 8px;
      padding: 15px;
      margin: 15px 0;
      max-height: 400px;
      overflow-y: auto;
      font-family: 'Monaco', 'Consolas', monospace;
      font-size: 14px;
      line-height: 1.4;
    }
    .success { color: #4ade80; }
    .error { color: #f87171; }
    .info { color: #60a5fa; }
    .warning { color: #fbbf24; }
    h1 { text-align: center; margin-bottom: 30px; }
    .status-indicator {
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 8px;
      animation: pulse 2s infinite;
    }
    .status-online { background-color: #4ade80; }
    .status-offline { background-color: #f87171; }
    .status-checking { background-color: #fbbf24; }
    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    .progress {
      width: 100%;
      height: 6px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 3px;
      overflow: hidden;
      margin: 20px 0;
    }
    .progress-bar {
      height: 100%;
      background: linear-gradient(90deg, #4ade80, #60a5fa);
      border-radius: 3px;
      transition: width 0.3s ease;
      width: 0%;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>🚀 SceneLingo AI 集成测试</h1>
    
    <div>
      <h3>
        <span id="statusIndicator" class="status-indicator status-checking"></span>
        服务状态: <span id="statusText">检查中...</span>
      </h3>
    </div>

    <div class="progress">
      <div id="progressBar" class="progress-bar"></div>
    </div>

    <div>
      <button class="button" onclick="runHealthCheck()">🔍 健康检查</button>
      <button class="button" onclick="testBasicChat()">💬 基础聊天测试</button>
      <button class="button" onclick="testSceneGeneration()">🎭 场景生成测试</button>
      <button class="button" onclick="testWordDefinition()">📚 单词定义测试</button>
      <button class="button" onclick="runFullTest()">🚀 完整测试套件</button>
      <button class="button" onclick="clearResults()">🗑️ 清空结果</button>
    </div>

    <div id="results" class="result"></div>
  </div>

  <script>
    let testProgress = 0;
    let totalTests = 4;

    function updateProgress(progress) {
      const percentage = (progress / totalTests) * 100;
      document.getElementById('progressBar').style.width = percentage + '%';
    }

    function updateStatus(status, text) {
      const indicator = document.getElementById('statusIndicator');
      const statusText = document.getElementById('statusText');
      
      indicator.className = 'status-indicator status-' + status;
      statusText.textContent = text;
    }

    function log(message, type = 'info') {
      const results = document.getElementById('results');
      const timestamp = new Date().toLocaleTimeString();
      const colorClass = type;
      
      results.innerHTML += `<div class="${colorClass}">[${timestamp}] ${message}</div>`;
      results.scrollTop = results.scrollHeight;
    }

    function clearResults() {
      document.getElementById('results').innerHTML = '';
      testProgress = 0;
      updateProgress(0);
    }

    async function runHealthCheck() {
      log('🔍 开始健康检查...', 'info');
      updateStatus('checking', '检查中...');
      
      try {
        const response = await fetch('/api/ai/models');
        if (response.ok) {
          const data = await response.json();
          log('✅ AI 服务连接成功！', 'success');
          log(`📊 响应状态: ${response.status}`, 'success');
          log(`📋 可用模型: ${data.data?.[0]?.id || 'deepseek-chat'}`, 'info');
          updateStatus('online', '服务正常');
          return true;
        } else {
          log(`⚠️ 服务响应异常: ${response.status} ${response.statusText}`, 'warning');
          updateStatus('offline', '服务异常');
          return false;
        }
      } catch (error) {
        log(`❌ 连接失败: ${error.message}`, 'error');
        updateStatus('offline', '连接失败');
        return false;
      }
    }

    async function testBasicChat() {
      log('💬 开始基础聊天测试...', 'info');
      
      try {
        const response = await fetch('/api/ai/chat/completions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages: [
              { role: 'system', content: 'You are a helpful assistant. Respond briefly.' },
              { role: 'user', content: 'Say hello in JSON format like {"greeting": "Hello!", "status": "working"}' }
            ],
            temperature: 0.7,
            max_tokens: 100
          })
        });

        if (response.ok) {
          const data = await response.json();
          const content = data.choices?.[0]?.message?.content;
          log('✅ 基础聊天测试成功！', 'success');
          log(`🤖 AI 响应: ${content}`, 'info');
          testProgress++;
          updateProgress(testProgress);
          return true;
        } else {
          log(`❌ 聊天测试失败: ${response.status}`, 'error');
          return false;
        }
      } catch (error) {
        log(`❌ 聊天测试异常: ${error.message}`, 'error');
        return false;
      }
    }

    async function testSceneGeneration() {
      log('🎭 开始场景生成测试...', 'info');
      
      const prompt = `请为英语学习者创建一个包含单词 cat, house, book 的学习场景。返回JSON格式：
      {
        "title": "场景标题",
        "description": "场景描述",
        "words": ["cat", "house", "book"]
      }`;

      try {
        const response = await fetch('/api/ai/chat/completions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages: [
              { role: 'system', content: 'You are an English learning assistant. Always respond in valid JSON format.' },
              { role: 'user', content: prompt }
            ],
            temperature: 0.7,
            max_tokens: 500
          })
        });

        if (response.ok) {
          const data = await response.json();
          const content = data.choices?.[0]?.message?.content;
          log('✅ 场景生成测试成功！', 'success');
          log(`🎬 生成的场景: ${content.substring(0, 200)}...`, 'info');
          testProgress++;
          updateProgress(testProgress);
          return true;
        } else {
          log(`❌ 场景生成失败: ${response.status}`, 'error');
          return false;
        }
      } catch (error) {
        log(`❌ 场景生成异常: ${error.message}`, 'error');
        return false;
      }
    }

    async function testWordDefinition() {
      log('📚 开始单词定义测试...', 'info');
      
      const prompt = `请为英语单词 "beautiful" 提供定义。返回JSON格式：
      {
        "word": "beautiful",
        "definition": "中文释义",
        "pronunciation": "音标",
        "examples": ["例句1", "例句2"]
      }`;

      try {
        const response = await fetch('/api/ai/chat/completions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages: [
              { role: 'system', content: 'You are an English dictionary assistant. Always respond in valid JSON format.' },
              { role: 'user', content: prompt }
            ],
            temperature: 0.3,
            max_tokens: 300
          })
        });

        if (response.ok) {
          const data = await response.json();
          const content = data.choices?.[0]?.message?.content;
          log('✅ 单词定义测试成功！', 'success');
          log(`📖 单词定义: ${content.substring(0, 150)}...`, 'info');
          testProgress++;
          updateProgress(testProgress);
          return true;
        } else {
          log(`❌ 单词定义失败: ${response.status}`, 'error');
          return false;
        }
      } catch (error) {
        log(`❌ 单词定义异常: ${error.message}`, 'error');
        return false;
      }
    }

    async function runFullTest() {
      clearResults();
      log('🚀 开始完整的 AI 服务测试套件...', 'info');
      log('==================================================', 'info');
      
      testProgress = 0;
      updateProgress(0);

      // 健康检查
      const healthOk = await runHealthCheck();
      if (!healthOk) {
        log('❌ 健康检查失败，跳过其他测试', 'error');
        return;
      }

      await new Promise(resolve => setTimeout(resolve, 500)); // 短暂延迟

      // 基础聊天测试
      await testBasicChat();
      await new Promise(resolve => setTimeout(resolve, 500));

      // 场景生成测试
      await testSceneGeneration();
      await new Promise(resolve => setTimeout(resolve, 500));

      // 单词定义测试
      await testWordDefinition();

      log('', 'info');
      log('==================================================', 'info');
      log('✅ 测试套件执行完成！', 'success');
      
      if (testProgress === totalTests) {
        log('🎉 所有测试通过！您的 AI 集成完全正常工作！', 'success');
        updateStatus('online', '完全正常');
      } else {
        log(`⚠️ ${testProgress}/${totalTests} 个测试通过`, 'warning');
        updateStatus('offline', '部分异常');
      }
    }

    // 页面加载时自动进行健康检查
    window.onload = function() {
      setTimeout(runHealthCheck, 1000);
    };
  </script>
</body>
</html>
